<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar title="黑马头条-登录" >
    <template #left>
        <img class="logo" src="@/assets/images/logo.png">
    </template>
   </van-nav-bar>
   <!-- 登录表单 -->
  <div class="login-container">
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[{ required: true, message: '请填写手机号', trigger: 'onChange', pattern: /^1[3-9]\d{9}$/  }]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写密码', trigger: 'onChange', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px;">
        <van-button
        :loading="isLoading"
         block
         round
         type="info"
         native-type="submit"
         loading-text="加载中..."
         >登录</van-button>

      </div>
    </van-form>
  </div>

  </div>
</template>

<script>
import { mapActions } from 'vuex'

import { Notify } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      isLoading: false,
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    ...mapActions(['asyncLoginAction']),
    async onSubmitFn () {
      this.isLoading = true
      // 发送请求
      try {
        // 捕获错误
        await this.asyncLoginAction({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        Notify({ type: 'success', message: '登录成功' })
        this.$router.replace({
          path: this.$route.query.from || '/layout'
        })
      } catch (err) {
        // 危险通知
        Notify({ type: 'danger', message: '密码或手机号不正确' })
        // 不管登录成功还是失败，都解析
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
    width: 100px;
    height: 30px;
}

</style>
